package com.itheima.reggie.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.EmployeeExcel;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/employee")
@EnableAspectJAutoProxy //开启AOP
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 用户登录
     *
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("用户登陆，用户信息:{}", employee);
        //1.将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2.根据页面提交的用户名username查询数据库
        //构建条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //构造查询条件
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        //获取查询结果
        Employee emp = employeeService.getOne(queryWrapper);
        //3.如果没有查询到则返回登陆失败结果
        if (emp == null) {
            return R.error("登陆失败");
        }
        //4.密码比对，如果不一致则返回登陆失败结果
        if (!emp.getPassword().equals(password)) {
            return R.error("密码不一致，登陆失败");
        }
        //5.查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (emp.getStatus() == 0) {
            return R.error("该账号已被禁用！");
        }
        //6.登陆成功，将员工id存入Session并返回登陆成功结果
        request.getSession().setAttribute("employee", emp.getId());

        return R.success(emp);
    }

    /**
     * 用户退出
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        log.info("用户退出...");
        //清理Session中保存的当前登陆用户的id
        request.getSession().removeAttribute("employee");
        return R.success("退出成功！");
    }

    /**
     * 新增员工
     *
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request,@RequestBody Employee employee) {
        //设置初始密码123456，需要进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //获得当前登录用户的id
        Long empId = (Long) request.getSession().getAttribute("employee");
        //设置创建时间
        //employee.setCreateTime(LocalDateTime.now());
        //设置更新时间
        //employee.setUpdateTime(LocalDateTime.now());
        //设置创建人
        //employee.setCreateUser(empId);
        //设置修改人
        //employee.setUpdateUser(empId);

        log.info("新增员工信息为：{}", employee);

        employeeService.save(employee);
        return R.success("员工信息添加成功！");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize,String name){
        log.info("page={},pageSize={},name={}",page,pageSize,name);
        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //执行查询
        employeeService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 根据id修改员工信息
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
        log.info(employee.toString());
        //获取当前登陆员工id
        //Long empId = (Long) request.getSession().getAttribute("employee");
        //设置id为当前登陆用户id
        //employee.setUpdateUser(empId);
        //设置更新时间
        //employee.setUpdateTime(LocalDateTime.now());
        //调用Service方法，更新员工信息

        long id = Thread.currentThread().getId();
        log.info("线程id为：{}",id);

        employeeService.updateById(employee);
        return R.success("员工信息修改成功");
    }

    /**
     * 根据id查询员工信息(回显数据）
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("根据id查询员工信息...该员工ID为：{}",id);
        Employee employee = employeeService.getById(id);
        if(employee!=null){
            return R.success(employee);
        }
        return R.error("没有查询到对应员工信息.");
    }

    @GetMapping("/export")
    public void testWriteExcel2(HttpServletResponse response) {
        try {
            //  设置内容格式 以及 编码方式
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            //   调用service去获取数据
            LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
            List<Employee> resultList= employeeService.list(queryWrapper);
            //  使用java8新特性的stream流去处理数据，把空的数据过滤掉
            List<EmployeeExcel> resultBo = resultList.stream().filter(Objects::nonNull)
                    .map(t -> {

                        Long createUser = t.getCreateUser();
                        Employee creat = employeeService.getById(createUser);
                        String creatName = creat.getName();

                        Long updateUser = t.getUpdateUser();
                        Employee uodate = employeeService.getById(updateUser);
                        String updateName = uodate.getName();

                        return EmployeeExcel.builder()
                                .id(t.getId().toString())
                                .username(t.getUsername())
                                .name(t.getName())
                                .phone(t.getPhone())
                                .sex(t.getSex().equals("1")?"男":"女")
                                .idNumber(t.getIdNumber())
                                .status(t.getStatus()==1?"启用":"禁用")
                                .createTime(t.getCreateTime())
                                .updateTime(t.getUpdateTime())
                                .createUser(creatName)
                                .updateUser(updateName)
                                .build();
                    }).collect(Collectors.toList());
            //  设置文件名称
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("employee", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
            //  sheet名称
            EasyExcel.write(response.getOutputStream(), EmployeeExcel.class).sheet("测试导出").doWrite(resultBo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
